package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.jetcache.utils.JetCacheUtils;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.base.common.constants.BaseCache;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.system.core.dao.model.SysUser;
import com.bifang.module.system.core.dao.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.enums.EduSynDyApplyDictEnum;
import com.jwsoft.manager.common.enums.EnrollStatusFormalEnum;
import com.jwsoft.manager.common.vo.common.AreaControlVO;
import com.jwsoft.manager.common.vo.eduDyjyQuerySync.DySyncResult;
import com.jwsoft.manager.common.vo.eduStudentEnroll.EduStudentEnrollVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyApplyKeyVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyApplyQueryVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyApplyVO;
import com.jwsoft.manager.common.vo.eduSyncDyApply.EduSyncDyCommonVO;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduSyncDyApply;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollService;
import com.jwsoft.manager.core.dao.service.EduSyncDyApplyService;
import com.jwsoft.manager.core.integration.EduSyncDyApplyIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import com.jwsoft.manager.core.util.dySync.CallUtils;
import com.jwsoft.manager.core.util.dySync.JsonUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.*;

/**
 * 东阳市报名专库同步情况表业务实现类
 *
 * @author wangt
 * @since 2024-06-11
 */
@ApiService(funcCode = "eduSyncDyApply", title = "东阳市报名专库同步情况表")
public class EduSyncDyApplyIntegrationImpl implements EduSyncDyApplyIntegration {

    @Autowired
    public EduSyncDyApplyService eduSyncDyApplyService;

    @Autowired
    private EduHelper eduHelper;

    @Autowired
    private DictHelper dictHelper;

    @Autowired
    private EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduDyjyQuerySyncIntegrationImpl dyjyQuerySyncIntegration;
    @Autowired
    private CallUtils callUtils;

    @Autowired
    private SysUserService sysUserService;

    @Override
    @OpApi(funcCode = "eduSyncDyApply0001", title = "东阳市报名专库同步情况表分页查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduSyncDyApplyVO> getList(EduSyncDyApplyQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        QueryWrapper<EduSyncDyApply> eduSyncDyApplyQueryWrapper = new QueryWrapper<>();
        eduSyncDyApplyQueryWrapper.lambda()
                .eq(!ObjectUtils.isEmpty(vo.getYear()),EduSyncDyApply::getYear,vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getIdcard()),EduSyncDyApply::getIdcard,vo.getIdcard());
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        List<EduSyncDyApply> list = eduSyncDyApplyService.list(eduSyncDyApplyQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduSyncDyApply> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduSyncDyApplyVO> resultList = Convert.toList(EduSyncDyApplyVO.class, pageInfo.getList());
        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduSynDyApplyDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0002", title = "东阳市报名专库同步情况表根据主键查询详情", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSyncDyApplyVO getById(EduSyncDyApplyKeyVO vo) {
        EduSyncDyApply entity = eduSyncDyApplyService.getById(vo.getJhApplyId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduSyncDyApplyVO result = Convert.convert(EduSyncDyApplyVO.class, entity);
        return result;
    }

    /**
     * 保存前统一校验
     */
    @Override
    @OpApi(funcCode = "eduSyncDyApply0003", title = "东阳市报名专库同步情况表保存前校验", funcType = FuncTypeEnum.other, checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduSyncDyApplyVO vo) {
        //主键为空为新增校验
        if (StringUtils.isEmpty(vo.getIdcard())) {
            throw new AppException("身份证不能为空");
        }
        // 设置默认年份
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }
        //主键不为空为修改校验
        //一年一个身份证只有一条数据
        validateSingleEntryPerYear(vo);
    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0004", title = "东阳市报名专库同步情况表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduSyncDyApply0004",
            operationName = "东阳市报名专库同步情况表新增",
            dataType = "jhApplyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncDyApplyVO add(EduSyncDyApplyVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSyncDyApply entity = Convert.convert(EduSyncDyApply.class, vo);
        eduSyncDyApplyService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setJhApplyId(entity.getJhApplyId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0005", title = "东阳市报名专库同步情况表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduSyncDyApply0005",
            operationName = "东阳市报名专库同步情况表修改",
            dataType = "jhApplyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduSyncDyApplyVO edit(EduSyncDyApplyVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhApplyId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduSyncDyApply oldEntity = eduSyncDyApplyService.getById(vo.getJhApplyId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        EduSyncDyApply entity = Convert.convert(EduSyncDyApply.class, vo);
        eduSyncDyApplyService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0006", title = "东阳市报名专库同步情况表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduSyncDyApply0006",
            operationName = "东阳市报名专库同步情况表删除",
            dataType = "jhApplyId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduSyncDyApplyKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getJhApplyId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduSyncDyApply entity = eduSyncDyApplyService.getById(vo.getJhApplyId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduSyncDyApplyService.removeById(vo.getJhApplyId());
    }


    @Override
    @OpApi(funcCode = "eduSyncDyApply0007", title = "输入身份证查询报名信息", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSyncDyCommonVO getListByIdCard(EduSyncDyApplyQueryVO vo) {
        EduSyncDyCommonVO eduSyncDyCommonVO = new EduSyncDyCommonVO();

        // 校验输入参数
        if (StringUtils.isEmpty(vo.getIdcard())) {
            throw new AppException("身份证不能为空");
        }
        // 设置默认年份
        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }

        // 查询报名成功的学生信息
        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduStudentEnroll::getIdcard, vo.getIdcard())
                .eq(EduStudentEnroll::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getEnrollStatus()),EduStudentEnroll::getEnrollStatus, vo.getEnrollStatus());

        List<EduStudentEnroll> enrollList = eduStudentEnrollService.list(queryWrapper);
        if (CollectionUtils.isEmpty(enrollList)) {
            return eduSyncDyCommonVO;
        }
        // 获取第一条记录
        EduStudentEnroll one = enrollList.get(0);
        if (ObjectUtils.isEmpty(one)) {
            return eduSyncDyCommonVO;
        }
        // 复制属性并转换性别
        BeanUtils.copyProperties(one, eduSyncDyCommonVO);
        eduSyncDyCommonVO.setName(one.getFullName());
        eduSyncDyCommonVO.setResidentialAddress(one.getAddress());
        if ("1".equalsIgnoreCase(one.getSex())){
            eduSyncDyCommonVO.setSex("0");
        }else{
            eduSyncDyCommonVO.setSex("1");
        }
        eduSyncDyCommonVO.setNation("01");
        eduSyncDyCommonVO.setBmSyncFlag("0");
        eduSyncDyCommonVO.setHouseholdType("1");
        eduSyncDyCommonVO.setApplyTime(one.getCreateTime().getTime());
        eduSyncDyCommonVO.setApplyCountyCode(one.getAreaCode());
        eduSyncDyCommonVO.setEnrollTime(eduSyncDyCommonVO.getAdmitTime());
        eduSyncDyCommonVO.setEntranceType(eduSyncDyCommonVO.getSource());
        eduSyncDyCommonVO.setEnrollState(eduSyncDyCommonVO.getEnrollStatus());
        eduSyncDyCommonVO.setEnrollSchoolName(eduSyncDyCommonVO.getSchoolName());
        eduSyncDyCommonVO.setEnrollSchoolCode(eduSyncDyCommonVO.getSchoolId());


        //多表联差userName
        SysUser sysUser = sysUserService.getById(eduSyncDyCommonVO.getAdmitUserId());
        if(!ObjectUtils.isEmpty(sysUser)){
            eduSyncDyCommonVO.setEnrollHuman(sysUser.getFullName());
        }
        //转换第一第二监护人
        if(StringUtils.isNotBlank(one.getFatherIdcard())){
            eduSyncDyCommonVO.setMasterGuardianName(one.getFatherName());
            eduSyncDyCommonVO.setMasterGuardianNumber(one.getFatherIdcard());
            eduSyncDyCommonVO.setMasterGuardianRelation("1");
            if(StringUtils.isNotBlank(one.getMotherIdcard())){
                eduSyncDyCommonVO.setSlaveGuardianName(one.getMotherName());
                eduSyncDyCommonVO.setSlaveGuardianNumber(one.getMotherIdcard());
                eduSyncDyCommonVO.setSlaveGuardianRelation("2");
            }
        }else{
            eduSyncDyCommonVO.setMasterGuardianName(one.getMotherName());
            eduSyncDyCommonVO.setMasterGuardianNumber(one.getMotherIdcard());
            eduSyncDyCommonVO.setMasterGuardianRelation("2");
        }

        return eduSyncDyCommonVO;
    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0008", title = "批量生成同步到金华的报名库信息", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public void addBatch(EduSyncDyApplyQueryVO vo) {
        String redisKey="dyedu:syncDyApply:batch";
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("正在批量处理中......");
        }
        redisHelper.set(redisKey,"1",1800);
        try {
            if (vo.getAllFlag()==null){
                vo.setAllFlag(false);
            }
            String areaCode=vo.getApplyCountyCode();
            if(StringUtils.isBlank(areaCode)){
                areaCode= SessionUtil.getAreaCode();
            }
            if(StringUtils.isBlank(areaCode)){
                areaCode=eduHelper.thisAreaCode();
            }
            Integer year=eduHelper.thisYear();
            List<String> enrollStatusList=new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            LambdaQueryWrapper<EduStudentEnroll> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.select(EduStudentEnroll::getFullName,EduStudentEnroll::getIdcard,EduStudentEnroll::getYear,
                    EduStudentEnroll::getAreaCode,EduStudentEnroll::getSchoolNature,
                    EduStudentEnroll::getSex,EduStudentEnroll::getHouseholdPlace,EduStudentEnroll::getCardType,
                    EduStudentEnroll::getSchoolCategory,EduStudentEnroll::getCreateTime,EduStudentEnroll::getBirthYmd,
                    EduStudentEnroll::getAddress,EduStudentEnroll::getFatherIdcard,EduStudentEnroll::getFatherName,
                    EduStudentEnroll::getMotherIdcard,EduStudentEnroll::getMotherName).eq(EduStudentEnroll::getAreaCode,areaCode)
                    .eq(EduStudentEnroll::getYear,year)
                    .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
            if(vo.getAllFlag()){
                queryWrapper.notInSql(EduStudentEnroll::getIdcard,"select idcard from edu_sync_dy_apply where year="+year+" and del='0' ");
            }
            List<EduStudentEnroll> list=eduStudentEnrollService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)){
                Long importBatchId=IdWorker.getId();
                Map<String,String> map=new HashMap<>();
                for (EduStudentEnroll eduStudentEnroll:list){
                    if (map.containsKey(eduStudentEnroll.getIdcard())){
                        continue;
                    }
                    map.put(eduStudentEnroll.getIdcard(),eduStudentEnroll.getFullName());
                    EduSyncDyApply eduSyncDyApply=new EduSyncDyApply();
                    QueryWrapper<EduSyncDyApply> applyQueryWrapper=new QueryWrapper<>();
                    applyQueryWrapper.lambda().select(EduSyncDyApply::getJhApplyId).eq(EduSyncDyApply::getIdcard,eduStudentEnroll.getIdcard())
                            .eq(EduSyncDyApply::getYear,eduStudentEnroll.getYear())
                            .eq(EduSyncDyApply::getApplyCountyCode,eduStudentEnroll.getAreaCode());
                    List<EduSyncDyApply> applyList=eduSyncDyApplyService.list(applyQueryWrapper);
                    if (!CollectionUtils.isEmpty(applyList)){
                        eduSyncDyApply.setJhApplyId(applyList.get(0).getJhApplyId());
                    }

                    eduSyncDyApply.setBmSyncFlag("0");
                    eduSyncDyApply.setYear(eduStudentEnroll.getYear());
                    eduSyncDyApply.setApplyTime(eduStudentEnroll.getCreateTime().getTime());
                    eduSyncDyApply.setName(eduStudentEnroll.getFullName());
                    eduSyncDyApply.setCardType(eduStudentEnroll.getCardType());
                    eduSyncDyApply.setIdcard(eduStudentEnroll.getIdcard());
                    eduSyncDyApply.setImportBatchId(importBatchId);
                    eduSyncDyApply.setNation("01");
                    if ("1".equalsIgnoreCase(eduStudentEnroll.getSex())){
                        eduSyncDyApply.setSex("0");
                    }else{
                        eduSyncDyApply.setSex("1");
                    }
                    eduSyncDyApply.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
                    eduSyncDyApply.setApplyCountyCode(eduStudentEnroll.getAreaCode());
                    eduSyncDyApply.setHouseholdAddress(eduStudentEnroll.getHouseholdPlace());
                    eduSyncDyApply.setHouseholdType("1");
                    eduSyncDyApply.setResidentialAddress(eduStudentEnroll.getAddress());
                    if(StringUtils.isNotBlank(eduStudentEnroll.getFatherIdcard())){
                        eduSyncDyApply.setMasterGuardianName(eduStudentEnroll.getFatherName());
                        eduSyncDyApply.setMasterGuardianNumber(eduStudentEnroll.getFatherIdcard());
                        eduSyncDyApply.setMasterGuardianRelation("1");
                        if(StringUtils.isNotBlank(eduStudentEnroll.getMotherIdcard())){
                            eduSyncDyApply.setSlaveGuardianName(eduStudentEnroll.getMotherName());
                            eduSyncDyApply.setSlaveGuardianNumber(eduStudentEnroll.getMotherIdcard());
                            eduSyncDyApply.setSlaveGuardianRelation("2");
                        }
                    }else{
                        eduSyncDyApply.setMasterGuardianName(eduStudentEnroll.getMotherName());
                        eduSyncDyApply.setMasterGuardianNumber(eduStudentEnroll.getMotherIdcard());
                        eduSyncDyApply.setMasterGuardianRelation("2");
                    }
                    eduSyncDyApplyService.saveOrUpdate(eduSyncDyApply);
                }
            }
        }catch (Exception e){
            throw new AppException("批量生成同步到金华报名库数据系统异常"+e.getMessage(),e);
        }finally {
            redisHelper.del(redisKey);
        }



    }

    @Override
    @OpApi(funcCode = "eduSyncDyApply0009", title = "金华市报名同步学生信息保存",
            funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public EduSyncDyApply saveBm(EduStudentEnrollVO eduStudentEnroll) {
        QueryWrapper<EduSyncDyApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncDyApply::getYear, eduStudentEnroll.getYear())
                .eq(EduSyncDyApply::getIdcard,eduStudentEnroll.getIdcard())
                .eq(EduSyncDyApply::getApplyCountyCode,eduStudentEnroll.getAreaCode());
        List<EduSyncDyApply> eduSyncDyApplyList = eduSyncDyApplyService.list(queryWrapper);
        EduSyncDyApply eduSyncDyApply = null;
        Long importBatchId=IdWorker.getId();
        if(!CollectionUtils.isEmpty(eduSyncDyApplyList)){
            eduSyncDyApply = eduSyncDyApplyList.get(0);
            if(BoolEnum.FALSE.getType().equals(eduSyncDyApply.getBmSyncFlag())){
                try {
                    saveSyncStudentApplyInfo(eduSyncDyApply);
                    eduSyncDyApply.setBmSyncFlag("1");
                    eduSyncDyApply.setBmSyncRemark("报名上传成功");
                }catch (Exception e){
                    String msg=e.getMessage();
                    if(msg.length()>300){
                        msg=msg.substring(0,200);
                    }
                    eduSyncDyApply.setBmSyncFlag("2");
                    eduSyncDyApply.setBmSyncRemark(msg);
                }
            }
        }else {
            eduSyncDyApply.setBmSyncFlag("0");
            eduSyncDyApply.setYear(eduStudentEnroll.getYear());
            eduSyncDyApply.setApplyTime(eduStudentEnroll.getCreateTime().getTime());
            eduSyncDyApply.setName(eduStudentEnroll.getFullName());
            eduSyncDyApply.setCardType(eduStudentEnroll.getCardType());
            eduSyncDyApply.setIdcard(eduStudentEnroll.getIdcard());
            eduSyncDyApply.setImportBatchId(importBatchId);
            eduSyncDyApply.setNation("01");
            if ("1".equalsIgnoreCase(eduStudentEnroll.getSex())){
                eduSyncDyApply.setSex("0");
            }else{
                eduSyncDyApply.setSex("1");
            }
            eduSyncDyApply.setSchoolCategory(eduStudentEnroll.getSchoolCategory());
            eduSyncDyApply.setApplyCountyCode(eduStudentEnroll.getAreaCode());
            eduSyncDyApply.setHouseholdAddress(eduStudentEnroll.getHouseholdPlace());
            eduSyncDyApply.setHouseholdType("1");
            eduSyncDyApply.setResidentialAddress(eduStudentEnroll.getAddress());
            if(StringUtils.isNotBlank(eduStudentEnroll.getFatherIdcard())){
                eduSyncDyApply.setMasterGuardianName(eduStudentEnroll.getFatherName());
                eduSyncDyApply.setMasterGuardianNumber(eduStudentEnroll.getFatherIdcard());
                eduSyncDyApply.setMasterGuardianRelation("1");
                if(StringUtils.isNotBlank(eduStudentEnroll.getMotherIdcard())){
                    eduSyncDyApply.setSlaveGuardianName(eduStudentEnroll.getMotherName());
                    eduSyncDyApply.setSlaveGuardianNumber(eduStudentEnroll.getMotherIdcard());
                    eduSyncDyApply.setSlaveGuardianRelation("2");
                }
            }else{
                eduSyncDyApply.setMasterGuardianName(eduStudentEnroll.getMotherName());
                eduSyncDyApply.setMasterGuardianNumber(eduStudentEnroll.getMotherIdcard());
                eduSyncDyApply.setMasterGuardianRelation("2");
            }
            try {
                saveSyncStudentApplyInfo(eduSyncDyApply);
                eduSyncDyApply.setBmSyncFlag("1");
                eduSyncDyApply.setBmSyncRemark("报名上传成功");
            }catch (Exception e){
                String msg=e.getMessage();
                if(msg.length()>300){
                    msg=msg.substring(0,200);
                }
                eduSyncDyApply.setBmSyncFlag("2");
                eduSyncDyApply.setBmSyncRemark(msg);
            }
        }
        eduSyncDyApplyService.saveOrUpdate(eduSyncDyApply);
        return eduSyncDyApply;


    }

    @Override
    public int eduJhjyBmSync(AreaControlVO vo) {
        String redisKey="dyedu:syncDyApply:batchSync";
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("正在批量同步金华报名数据处理中......");
        }
        redisHelper.set(redisKey,"1",1800);
        Integer year=eduHelper.thisYear();
        if (StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(eduHelper.thisAreaCode());
        }
        QueryWrapper<EduSyncDyApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduSyncDyApply::getYear, year)
                .eq(EduSyncDyApply::getApplyCountyCode,vo.getAreaCode())
                .eq(EduSyncDyApply::getBmSyncFlag,BoolEnum.FALSE.getType());
        List<EduSyncDyApply> list=eduSyncDyApplyService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)){
            QueryWrapper<EduSyncDyApply> queryWrapperError = new QueryWrapper<>();
            queryWrapperError.lambda().eq(EduSyncDyApply::getYear, year)
                    .eq(EduSyncDyApply::getApplyCountyCode,vo.getAreaCode())
                    .eq(EduSyncDyApply::getBmSyncFlag,"2");
            List<EduSyncDyApply> errorList=eduSyncDyApplyService.list(queryWrapperError);
            if(CollectionUtils.isEmpty(errorList)){
                redisHelper.del(redisKey);
                return 0;
            }
            list=errorList;
        }
        int i=0;
        for(EduSyncDyApply apply:list){
            try {
                saveSyncStudentApplyInfo(apply);
                apply.setBmSyncFlag("1");
                apply.setBmSyncRemark("成功");
                eduSyncDyApplyService.updateById(apply);
                i++;
            }catch (AppException e){
                apply.setBmSyncFlag("2");
                String msg=e.getMsg();
                if (StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,300);
                }
                apply.setBmSyncRemark(msg);
                eduSyncDyApplyService.updateById(apply);
            }catch (Exception e){
                apply.setBmSyncFlag("2");
                String msg=e.getMessage();
                if (StringUtils.isNotBlank(msg)&&msg.length()>300){
                    msg=msg.substring(0,300);
                }
                apply.setBmSyncRemark(msg);
                eduSyncDyApplyService.updateById(apply);
            }

        }
        redisHelper.del(redisKey);
        return i;
    }


    private void saveSyncStudentApplyInfo(EduSyncDyApply vo) {


        Map<String, Object> params = BeanUtil.beanToMap(vo, false, true);

        if (vo.getApplyTime() == null) {
            throw new AppException("报名时间不能为空");
        } else {
            params.put("applyDate", DateUtil.format(DateUtil.date(vo.getApplyTime()), "yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.isBlank(vo.getCardType())) {
            throw new AppException("证件类型不能为空");
        }
        if (StringUtils.isBlank(vo.getName())) {
            throw new AppException("学生姓名不能为空");
        }
        if (StringUtils.isBlank(vo.getSchoolCategory())) {
            throw new AppException("学段不能为空");
        }
        if (StringUtils.isBlank(vo.getIdcard())) {
            throw new AppException("学生证件号码不能为空");
        }
        if (StringUtils.isBlank(vo.getApplyCountyCode())) {
            throw new AppException("报名所在区县码不能为空");
        }
        //map转string
        String paramsStr = JsonUtil.toJsonString(params);
        //将传入参数 进行签名
        String timestamp = String.valueOf(System.currentTimeMillis());
        //参数进行加密
        String appKey = dyjyQuerySyncIntegration.getCommon("dy_sync_appKey");
        String encrypt = callUtils.encrypt(paramsStr, appKey);
        //根据参数，密钥，时间生成签名
        String appSecret = dyjyQuerySyncIntegration.getCommon("dy_sync_appSecret");

        String accessToken = "";
        Cache<String,String> tokenCache = JetCacheUtils.create(BaseCache.CACHE_ACCESS_TOKEN_CLIENT, CacheType.BOTH, Duration.ofSeconds(1500L),Duration.ofSeconds(60));
        String redisKey=vo.getApplyCountyCode()+vo.getYear();
        accessToken  = tokenCache.get(redisKey);
        if (StringUtils.isBlank(accessToken)) {
            //调用获取token方法，得到token信息
            DySyncResult token = dyjyQuerySyncIntegration.getToken();
            accessToken = (String) token.getData().get("accessToken");
            tokenCache.put(redisKey, accessToken);
        }
        if (StringUtils.isBlank(accessToken)) {
            throw new AppException("accessToken不能为空");
        }
        //加密传参
        HashMap<String, String> map = new HashMap<>();
        map.put("cryptoStr", encrypt);

        String cryptoStr = JSONObject.toJSONString(map);
        String signature = callUtils.getSign(cryptoStr, appSecret, timestamp);
        if (StringUtils.isBlank(signature)) {
            throw new AppException("签名不能为空");
        }
        //调用同步删除接口
        String reqUrl = dyjyQuerySyncIntegration.getCommon("dy_sync_reqUrl");
        String appId = dyjyQuerySyncIntegration.getCommon("dy_sync_appId");
        String url = reqUrl + "syncSaveJhApply0001";
        String data = encrypt;
        HttpResponse execute = HttpRequest.post(url)
                //设置请求体
                .header("Content-Type", "application/json")
                .header("signature", signature)
                .header("timestamp", timestamp)
                .header("accessToken", accessToken)
                .header("appId", appId)
                .setReadTimeout(10000)
                .body(cryptoStr) //加密
                .execute();
        String body = execute.body();
        if (StringUtils.isBlank(body)) {
            throw new AppException("请求接口失败失败，未返回信息");
        }
        JSONObject jsonBody = JSONObject.parseObject(body);
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getInteger("code") != 0) {
                if ("401".equals(jsonObject.getString("code")) || "456".equals(jsonObject.getString("code"))) {
                    //调用获取token方法，得到token信息
                    DySyncResult token = dyjyQuerySyncIntegration.getToken();
                    accessToken = (String) token.getData().get("accessToken");
                    tokenCache.put(redisKey, accessToken);
                } else {
                    String errorMessage = (String) jsonObject.get("message");
                    throw new AppException("错误原因：" + errorMessage);
                }
            }
        }catch (AppException e){
            throw new AppException(e.getMsg());
        }catch (Exception e) {
            throw new AppException("请求接口失败失败：" + body);
        }
        //密文
        String encryptResult = (String) jsonObject.get("result");
        if (StringUtils.isNotBlank(encryptResult)){
            //对密文进行解密
            String decryptResult = callUtils.decrypt(encryptResult, appSecret);
            //解密后的密文转json
            JSONObject jsoncontent = JSONObject.parseObject(decryptResult);
            //转换json
            jsonBody.put("result", jsoncontent);
        }
    }

    // 校验每年一个身份证只有一条数据
    private void validateSingleEntryPerYear(EduSyncDyApplyVO vo) {
        QueryWrapper<EduSyncDyApply> applyQueryWrapper = new QueryWrapper<>();
        applyQueryWrapper.lambda()
                .eq(EduSyncDyApply::getIdcard, vo.getIdcard())
                .eq(EduSyncDyApply::getYear, vo.getYear())
                .ne(!ObjectUtils.isEmpty(vo.getJhApplyId()), EduSyncDyApply::getJhApplyId, vo.getJhApplyId());

        List<EduSyncDyApply> applyList = eduSyncDyApplyService.list(applyQueryWrapper);
        if (!CollectionUtils.isEmpty(applyList)) {
            throw new AppException("该身份证本年数据已存在");
        }
    }
}
